package com.example.threadstack;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.IntStream;

import static com.example.threadstack.Utils.getCurrentTime;
import static com.example.threadstack.Utils.sleepForMs;

@RestController
@RequestMapping("many-thread")
public class ManyThreadController {

    private ExecutorService executorService = Executors.newCachedThreadPool(new BasicThreadFactory
            .Builder()
            .namingPattern("Many-Thread-%d")
            .build()
    );

    @RequestMapping("/{tasks}")
    public DeferredResult<String> manyThreads(@PathVariable int tasks){
        DeferredResult<String> result = new DeferredResult<>(10 * 1000L, "TimeOut");
        CompletableFuture<String>[] futures = new CompletableFuture[tasks];
        for (int i=0;i<tasks;i++){
            futures[i] = CompletableFuture.supplyAsync(this::getValue, executorService);
        }
        CompletableFuture.allOf(futures).thenRun( ()-> result.setResult("SUCCESS"));
        return result;
    }

    private String getValue() {
        sleepForMs(50);
        return getCurrentTime();
    }
}
